package com.ejoysoft.wlanyz.business;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Vector;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.ejoysoft.common.DbConnect;
import com.ejoysoft.common.Globa;

public class LatlngCheck {
	private Globa globa;
    private DbConnect db;
    private Document document;
    private final String StatusOK = "OK";
    private Latlng obj;
    private static double EARTH_RADIUS = 6378137.0; //单位m
    private static final String baiduMapKey = "DF45D1401C31C5328897DE20D783E03930CCA49B";


    public LatlngCheck() {
    }

    public LatlngCheck(Globa globa) {
        this.globa = globa;
        db = globa.db;
    }

    public LatlngCheck(Globa globa, boolean b) {
        this.globa = globa;
        db = globa.db;
        if (b) globa.setDynamicProperty(this);
    }

    private static double rad(double d) { 
        return d * Math.PI / 180.0; 

    } 

    public static double getDistance(double lat1, double lng1, double lat2, double lng2) { 
        double radLat1 = rad(lat1); 
        double radLat2 = rad(lat2); 
        double a = radLat1 - radLat2; 
        double b = rad(lng1) - rad(lng2); 
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) 
                + Math.cos(radLat1) * Math.cos(radLat2) 
                * Math.pow(Math.sin(b / 2), 2))); 
        s = s * EARTH_RADIUS; 
        s = Math.round(s * 10000) / 10000.0; 
        BigDecimal bd = new BigDecimal(s);
	    s = bd.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();//保留一位小数
        return s; 
    } 
    public void checkLatlngs(){
    	obj = new  Latlng(globa);
    	String where = " where checkedLocation is null or checkedLocation =' ' ";
    	Vector<Latlng> vctObj = obj.list(where, 0, 0);
    	for(int i=0; i < vctObj.size(); i++){
    		Latlng obj1 = vctObj.get(i);
    		try
    		{
    			if(i !=0 && i % 10 == 0){
    				Thread.sleep(5000);//毫秒 
    			}
    		}
    		catch(Exception e){}
    		//latlngcheck(obj1.getStrId(), obj1.getAcName(), obj1.getOriginalLocation());
    		latlngcheckUsingBaidu(obj1.getStrId(), obj1.getAcName(), obj1.getOriginalLocation());
    		System.err.println("----------------i:"+i+":acnmae:"+obj1.getAcName()+":checkedLocation:"+obj1.getCheckedLocation());
    	}
    }
    
	/**
	 * 返回值的类型由 type决定
	 * @param expression
	 * @param type eg. XPathConstants.NODE/NODESET
	 * @return
	 * @throws XmlParserException
	 */
	public Object evaluate(String expression, QName type) {
		XPath xpath = XPathFactory.newInstance().newXPath();
		Object node = null;
		try {
			node = xpath.evaluate(expression, document, type);
		} catch (XPathExpressionException e) {
			System.err.println(e);
		}
		return node;
	}
	
    public void SimpleParser(InputStream is, String strId, String originalLatlng) throws IOException {
    	DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		builderFactory.setNamespaceAware(true);
		try {
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			document = builder.parse(is);
		} catch (Exception e) {
			System.err.println(e);
		}
	    String expression = "/GeocodeResponse/status";
	    Node node = (Node)evaluate(expression, XPathConstants.NODE);
	    String staus = node.getTextContent();
	    System.err.println("状态："+staus );
	    if(staus.equals(StatusOK)){
	        expression = "/GeocodeResponse/result";
	   	    NodeList nodeList = (NodeList)evaluate(expression, XPathConstants.NODESET);
	   	    System.err.println("节点数："+nodeList.getLength());
	   	    if(nodeList.getLength() == 1){
	   	    	expression = "/GeocodeResponse/result/geometry/location/lat";
	   	    	node = (Node)evaluate(expression, XPathConstants.NODE);
	   	    	String lat = node.getTextContent();
	   	    	expression = "/GeocodeResponse/result/geometry/location/lng";
	   	    	node = (Node)evaluate(expression, XPathConstants.NODE);
	   	    	String lng = node.getTextContent();
	   	    	System.err.println("经纬度："+lat+","+lng);
	   	    	obj.setCheckedLocation(lat+","+lng);
	   	 	if(originalLatlng !=null || "".equals(originalLatlng)){
	   	 		String arrayOriginalLatlng[] = originalLatlng.split(",");
	   	 		String originalLat = arrayOriginalLatlng[0];
	   	 		String originalLng = arrayOriginalLatlng[1];
	   	 		double lat1 = Double.parseDouble(lat);
	   	 		double lng1 = Double.parseDouble(lng);
	   	 		double lat2 = Double.parseDouble(originalLat);
	   	 		double lng2 = Double.parseDouble(originalLng);
	   	 		double distance = getDistance(lat1, lng1, lat2, lng2);
	   	 		System.err.println(lat+","+lng+"和"+originalLatlng+"的距离："+distance);
	   	 		obj.setDistance(distance);
	   	 	}else{
	   	 		obj.setDistance(0.0);
	   	 	}
	   	    	obj.update(strId);
	   	    }
	    }
	    else{
	    	System.err.println("地址解析失败：" + staus);
	    }
	 
	    
  }
   
    
   /*
    *google地址解析 
    * */
    public void latlngcheck(String strId, String address, String originalLatlng){
    	URL myURL = null;
    	try {
//    		String address ="扬州环境资源学院04#";
    		String ss ="";
    		try {
    			 ss=URLEncoder.encode(address,"UTF-8");//对地址进行编码
			} catch (Exception e) {
				// TODO: handle exception
				ss=address;
			}
    	myURL = new URL("http://ditu.google.cn/maps/api/geocode/xml?address=" +ss +"&sensor=false");
    	} catch (MalformedURLException e) {
    	// TODO Auto-generated catch block
    	e.printStackTrace();
    	}  
    	URLConnection httpsConn = null;
    	try {
	    	httpsConn = (URLConnection) myURL.openConnection();
	        InputStream is = httpsConn.getInputStream();
	        SimpleParser(is, strId, originalLatlng);
    	} catch (IOException e) {
   	      // TODO Auto-generated catch block
    		e.printStackTrace();
    	}  
    }
    
    /*
     *百度地址解析 
     * */
     public void latlngcheckUsingBaidu(String strId, String address, String originalLatlng){
     	URL myURL = null;
     	System.err.println("使用百度api");
     	try {
     		String ss ="";
     		try {
     			 ss=URLEncoder.encode(address,"UTF-8");//对地址进行编码
 			} catch (Exception e) {
 				// TODO: handle exception
 				ss=address;
 				
 			}
	//	String geocodingUrl = "http://api.map.baidu.com/geocoder?address="+ ss +"&output=xml&key="+ baiduMapKey +"&city=城市名"
		String geocodingUrl = "http://api.map.baidu.com/geocoder?address="+ ss +"&output=xml&key="+ baiduMapKey +"";
     	myURL = new URL(geocodingUrl);
     	} catch (MalformedURLException e) {
     	// TODO Auto-generated catch block
     	e.printStackTrace();
     	}  
     	URLConnection httpsConn = null;
     	try {
 	    	httpsConn = (URLConnection) myURL.openConnection();
 	        InputStream is = httpsConn.getInputStream();
 	       SimpleParserUsingBaidu(is, strId, originalLatlng);
     	} catch (IOException e) {
    	      // TODO Auto-generated catch block
     		e.printStackTrace();
     	}  
     }
     public void SimpleParserUsingBaidu(InputStream is, String strId, String originalLatlng) throws IOException {
     	DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
 		builderFactory.setNamespaceAware(true);
 		try {
 			DocumentBuilder builder = builderFactory.newDocumentBuilder();
 			document = builder.parse(is);
 		} catch (Exception e) {
 			System.err.println(e);
 		}
 	    String expression = "/GeocoderSearchResponse/status";
 	    Node node = (Node)evaluate(expression, XPathConstants.NODE);
 	    String staus = node.getTextContent();
 	    System.err.println("状态："+staus );
 	    if(staus.equals(StatusOK)){
 	        expression = "/GeocoderSearchResponse/result";
 	   	    NodeList nodeList = (NodeList)evaluate(expression, XPathConstants.NODESET);
 	   	    System.err.println("节点数："+nodeList.getLength());
 	   	    if(nodeList.getLength() == 1){
 	   	    	expression = "/GeocoderSearchResponse/result/location/lat";
 	   	    	node = (Node)evaluate(expression, XPathConstants.NODE);
 	   	    	String lat = node.getTextContent();
 	   	    	expression = "/GeocoderSearchResponse/result/location/lng";
 	   	    	node = (Node)evaluate(expression, XPathConstants.NODE);
 	   	    	String lng = node.getTextContent();
 	   	    	System.err.println("经纬度："+lat+","+lng);
 	   	    	obj.setCheckedLocation(lat+","+lng);
 	   	 	if(originalLatlng !=null || "".equals(originalLatlng)){
 	   	 		String arrayOriginalLatlng[] = originalLatlng.split(",");
 	   	 		String originalLat = arrayOriginalLatlng[0];
 	   	 		String originalLng = arrayOriginalLatlng[1];
 	   	 		double lat1 = Double.parseDouble(lat);
 	   	 		double lng1 = Double.parseDouble(lng);
 	   	 		double lat2 = Double.parseDouble(originalLat);
 	   	 		double lng2 = Double.parseDouble(originalLng);
 	   	 		double distance = getDistance(lat1, lng1, lat2, lng2);
 	   	 		System.err.println(lat+","+lng+"和"+originalLatlng+"的距离："+distance);
 	   	 		obj.setDistance(distance);
 	   	 	}else{
 	   	 		obj.setDistance(0.0);
 	   	 	}
 	   	    	obj.update(strId);
 	   	    }
 	    }
 	    else{
 	    	System.err.println("地址解析失败：" + staus);
 	    }
 	 
 	    
   }
    
}